<?php
	function pushData()
	{   
		$dbhost = '127.0.0.1';  // mysql服务器主机地址
		$dbuser = 'root';            // mysql用户名
		$dbpass = 'hwj199601';          // mysql password
		$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
		mysqli_query($conn, "set names utf8");
		mysqli_select_db( $conn, 'swoole' );
		mysqli_query($conn, "SET AUTOCOMMIT=0"); // 设置为不自动提交，因为MYSQL默认立即执行
		mysqli_begin_transaction($conn);    // 开始事务定义

		for ($i = 0; $i < 100000; $i++) {
			$str = 'lkskfsdjlsdjlfjsdlfjdslfjsdljfldsjfldsfjksldjflsdkflskfjldsfjldskfldskfldskjfsdkjfldskfdslfjlsdfjslkfjlsdjflskjflsdfjslfjlsslfjls';
			$sql = "insert into test values (null, '".$str."', '".$str."', '".$str."')";
			$res = mysqli_query($conn, $sql);
			if (!$res) {
				mysqli_query($conn, "ROLLBACK");     // 判断当执行失败时回滚
			}       
		}       
		mysqli_commit($conn);            //执行事务
		mysqli_close($conn);    
	}       

	$serv = new swoole_server('0.0.0.0', 9501);

	//设置异步进程数量
	$serv->set(array('task_worker_num' => 4));

	//投递异步任务
	$serv->on('receive', function($serv, $fd, $from_id, $data){
		var_dump($fd);
		$task_id = $serv->task($data);
		$serv->send($fd, "Receive: ".$data);
		echo "$task_id\n";
	});

	//处理异步任务
	$serv->on('task', function($serv, $task_id, $from_id, $data){
		echo "执行异步写入数据id: $task_id\n";
		pushData();
		$serv->finish("$data ->OK");
	});

	//处理结果
	$serv->on('finish', function($serv, $task_id, $data){
		echo "执行完成\n";
	});

	$serv->start();
